package com.fcwy.puzzle.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;

//import org.apache.http.HttpEntity;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

/**
 * 文件相关操作
 * 
 * @author lanyj
 */
public class HFile {
	private static final String TAG = "HFile";
	/**
	 * 根据文件路径 递归创建文件
	 * 
	 * @param file
	 */
	public static void createDipPath(String file) {
		String parentFile = file.substring(0, file.lastIndexOf("/"));
		File file1 = new File(file);
		File parent = new File(parentFile);
		if (!file1.exists()) {
			parent.mkdirs();
			try {
				file1.createNewFile();
				HLog.i(TAG,"Create new file :" + file);
			} catch (IOException e) {
				HLog.e(TAG, e.getMessage());
			}
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 */
	public static boolean deleteFile(String path) {
		boolean bl;
		File file = new File(path);
		if (file.exists()) {
			bl = file.delete();
		} else {
			bl = false;
		}
		return bl;
	}

	// 复制文件
	public static void copyFile(String sourcePath, String toPath) {
		File sourceFile = new File(sourcePath);
		File targetFile = new File(toPath);
		createDipPath(toPath);
		try {
			BufferedInputStream inBuff = null;
			BufferedOutputStream outBuff = null;
			try {
				// 新建文件输入流并对它进行缓冲
				inBuff = new BufferedInputStream(
						new FileInputStream(sourceFile));

				// 新建文件输出流并对它进行缓冲
				outBuff = new BufferedOutputStream(new FileOutputStream(
						targetFile));

				// 缓冲数组
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = inBuff.read(b)) != -1) {
					outBuff.write(b, 0, len);
				}
				// 刷新此缓冲的输出流
				outBuff.flush();
			} finally {
				// 关闭流
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 复制文件
	public static void copyFile(File sourceFile, File targetFile) {

		try {
			BufferedInputStream inBuff = null;
			BufferedOutputStream outBuff = null;
			try {
				// 新建文件输入流并对它进行缓冲
				inBuff = new BufferedInputStream(
						new FileInputStream(sourceFile));

				// 新建文件输出流并对它进行缓冲
				outBuff = new BufferedOutputStream(new FileOutputStream(
						targetFile));

				// 缓冲数组
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = inBuff.read(b)) != -1) {
					outBuff.write(b, 0, len);
				}
				// 刷新此缓冲的输出流
				outBuff.flush();
			} finally {
				// 关闭流
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 复制文件夹
	public static void copyDirectiory(String sourceDir, String targetDir)
			throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();
		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 源文件
				File sourceFile = file[i];
				// 目标文件
				File targetFile = new File(
						new File(targetDir).getAbsolutePath() + File.separator
								+ file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory()) {
				// 准备复制的源文件夹
				String dir1 = sourceDir + "/" + file[i].getName();
				// 准备复制的目标文件夹
				String dir2 = targetDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2);
			}
		}
	}

	/**
	 * 
	 * @param srcFileName
	 * @param destFileName
	 * @param srcCoding
	 * @param destCoding
	 * @throws IOException
	 */
	public static void copyFile(File srcFileName, File destFileName,
			String srcCoding, String destCoding) throws IOException {// 把文件转换为GBK文件
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					srcFileName), srcCoding));
			bw = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(destFileName), destCoding));
			char[] cbuf = new char[1024 * 5];
			int len = cbuf.length;
			int off = 0;
			int ret = 0;
			while ((ret = br.read(cbuf, off, len)) > 0) {
				off += ret;
				len -= ret;
			}
			bw.write(cbuf, 0, off);
			bw.flush();
		} finally {
			if (br != null)
				br.close();
			if (bw != null)
				bw.close();
		}
	}

	/**
	 * 删除目录下的所有文件
	 * 
	 * @param filepath
	 * @throws IOException
	 */
	public static void del(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组,并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
			}
		}
	}

	public static boolean copyTxtToSDCard(Context context, int fileForm,
			String toPath) {
		boolean copyResult = true;
		try {
			// File dir = new File(toPath);
			// 如果/sdcard/dictionary目录中存在,创建这个目录

			// 如果在/sdcard/dictionary目录中不存在
			// dictionary.db文件,则从res\raw目录中复制这个文件到
			// SD卡的目录(/sdcard/dictionary)

			// 获得封装dictionary.db文件的InputStream对象
			createDipPath(toPath);
			InputStream is = context.getResources().openRawResource(fileForm);
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			if (sb != null) {
				OutputStreamWriter fileOutputStream = new OutputStreamWriter(
						new FileOutputStream(new File(toPath)), "GBK");
				fileOutputStream.write(sb.toString());
				fileOutputStream.close();
				copyResult = true;
			} else {
				copyResult = false;
			}
			br.close();
			isr.close();
			is.close();
		} catch (Exception e) {
			copyResult = false;
		}
		return copyResult;
	}

	boolean flag = false;
	File file;
	long fileSize=0;
	/*** 获取文件大小 ***/
	public static long getFileSizes(File f) throws Exception {

		long s = 0;
		if (f.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(f);
			s = fis.available();
		} else {
			f.createNewFile();
			System.out.println("文件不存在");
		}
		return s;
	}

	/** 转换文件大小 **/
	public static String FormetFileSize(long fileS) {// 转换文件大小
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}
	public static String FormetDouble(double fileS) {// 转换字符格式
		DecimalFormat df = new DecimalFormat("#.0");
		String fileSizeString = df.format(fileS) ;
		return fileSizeString;
	}
	public static long getlist(File f) {// 递归求取目录文件个数
		long size = 0;
		File flist[] = f.listFiles();
		size = flist.length;
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getlist(flist[i]);
				size--;
			}
		}
		return size;
	}

	public boolean deleteDirectory(String dirPath) {// 删除目录(文件夹)以及目录下的文件
		// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!dirPath.endsWith(File.separator)) {
			dirPath = dirPath + File.separator;
		}
		File dirFile = new File(dirPath);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		flag = true;
		File[] files = dirFile.listFiles();// 获得传入路径下的所有文件
		for (int i = 0; i < files.length; i++) {// 循环遍历删除文件夹下的所有文件(包括子目录)
			if (files[i].isFile()) {// 删除子文件
				flag = deleteFile(files[i].getAbsolutePath());
				System.out.println(files[i].getAbsolutePath() + " 删除成功");
				if (!flag)
					break;// 如果删除失败,则跳出
			} else {// 运用递归,删除子目录
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;// 如果删除失败,则跳出
			}
		}
		if (!flag) {
			return false;
		} else {
			return true;
		}
	}

	public static void getAllFile(String dirPath){
		if (!dirPath.endsWith(File.separator)) {
			dirPath = dirPath + File.separator;
		}
		File dirFile = new File(dirPath);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			HLog.d(TAG, "no dirFile");
			return;
		}
		File[] files = dirFile.listFiles();// 获得传入路径下的所有文件
		for (int i = 0; i < files.length; i++) {// 循环遍历删除文件夹下的
			if (files[i].isFile()) {
				getAllFile(files[i].getAbsolutePath());
			}else{
				HLog.d(TAG, files[i].getAbsolutePath()+" :"+files[i].getName());
			}
		}
	}
	public static void downloadFile(final String url,final String filePath) {
		// 下载网络文件
		/*final File tempFile = new File(filePath);
		if (tempFile.exists())return;
		new Thread() {
			public void run() {
				try {
					HttpClient client = new DefaultHttpClient();
					// params[0]代表连接的url
					HttpGet get = new HttpGet(url);
					HttpResponse response = client.execute(get);
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();
					if (is != null) {
						createDipPath(filePath);
						// 已读出流作为参数创建一个带有缓冲的输出流
						BufferedInputStream bis = new BufferedInputStream(is);
						// 创建一个新的写入流，讲读取到的图像数据写入到文件中
						FileOutputStream fos = new FileOutputStream(tempFile);
						// 已写入流作为参数创建一个带有缓冲的写入流
						BufferedOutputStream bos = new BufferedOutputStream(fos);
						int read;
						byte[] buffer = new byte[1024];
						while ((read = bis.read(buffer)) != -1) {
							bos.write(buffer, 0, read);													
						}
						bos.flush();
						bos.close();
						fos.flush();
						fos.close();
						is.close();
						bis.close();
					}

				} catch (ClientProtocolException e) {
					HLog.i(TAG, "下载更新文件失败");
				} catch (IOException e) {
					HLog.i(TAG, "下载更新文件失败");
				} catch (Exception e) {
					HLog.i(TAG, "下载更新文件失败");
				}
			}
		}.start();*/

	}
	public static void downloadBookImg(final String url,final String filePath) {
		// 下载网络文件
		/*final File tempFile = new File(filePath);
		if (tempFile.exists())return;
		try {
			HttpClient client = new DefaultHttpClient();
			// params[0]代表连接的url
			HttpGet get = new HttpGet(url);
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			if (is != null) {
				createDipPath(filePath);
				// 已读出流作为参数创建一个带有缓冲的输出流
				BufferedInputStream bis = new BufferedInputStream(is);
				// 创建一个新的写入流，讲读取到的图像数据写入到文件中
				FileOutputStream fos = new FileOutputStream(tempFile);
				// 已写入流作为参数创建一个带有缓冲的写入流
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				int read;
				byte[] buffer = new byte[1024];
				while ((read = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, read);													
				}
				bos.flush();
				bos.close();
				fos.flush();
				fos.close();
				is.close();
				bis.close();
			}
			
		} catch (ClientProtocolException e) {
			HLog.i(TAG, "下载更新文件失败");
		} catch (IOException e) {
			HLog.i(TAG, "下载更新文件失败");
		} catch (Exception e) {
			HLog.i(TAG, "下载更新文件失败");
		}*/

	}
	/**
	 * 得到文件的缩略图
	 * @param imgPath
	 * @return
	 */
	public static String getSmallImg (String imgPath ){
		String newImg = imgPath.substring(0, imgPath.lastIndexOf(".")) + "_s"  + imgPath.substring(imgPath.lastIndexOf("."), imgPath.length());
		return newImg;
	}
	/**
	 * 杂志书城
	 * @param 
	 * @return
	 */
	private void sd() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { // 判断是否插入SD卡
			File filePath = Environment.getExternalStorageDirectory(); // 获得sd
																		// card的路径
			StatFs stat = new StatFs(filePath.getPath()); // 创建StatFs对象，这个对象很重要SD卡的信息就靠它获取了
			long blockSize = stat.getBlockSize(); // 获得block的大小
			float totalBlocks = stat.getBlockCount(); // 获得总容量
			int sizeInMb = (int) (blockSize * totalBlocks) / 1024 / 1024; // 转换成单位是兆的
			long availableBlocks = stat.getAvailableBlocks(); // 获得可用容量
			float percent = availableBlocks / totalBlocks; // 获得可用比例
			percent = (int) (percent * 1000); // 舍去多余小数位数
			String a = "SD Card使用情况：\n总容量：" + sizeInMb + "M。\n已用"
					+ (1000 - percent) / 10.0f + "% 可用" + percent / 10.f + "%。";
		} else {
		}
	}
	/** 获取SD路径 **/
	public static String getSDPath() {
		// 判断sd卡是否存在
		if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			File sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
			return sdDir.getPath();
		}
		return "/sdcard";
	}

//	/** 获取文件信息 **/
//	public static FileInfo getFileInfo(File f) {
//		FileInfo info = new FileInfo();
//		info.Name = f.getName();
//		info.IsDirectory = f.isDirectory();
//		calcFileContent(info, f);
//		return info;
//	}

//	/** 计算文件内容 **/
//	private static void calcFileContent(FileInfo info, File f) {
//		if (f.isFile()) {
//			info.Size += f.length();
//		}
//		if (f.isDirectory()) {
//			File[] files = f.listFiles();
//			if (files != null && files.length > 0) {
//				for (int i = 0; i < files.length; ++i) {
//					File tmp = files[i];
//					if (tmp.isDirectory()) {
//						info.FolderCount++;
//					} else if (tmp.isFile()) {
//						info.FileCount++;
//					}
//					if (info.FileCount + info.FolderCount >= 10000) { // 超过一万不计算
//						break;
//					}
//					calcFileContent(info, tmp);
//				}
//			}
//		}
//	}


	/** 合并路径 **/
	public static String combinPath(String path, String fileName) {
		return path + (path.endsWith(File.separator) ? "" : File.separator) + fileName;
	}

	/** 复制文件 **/
	public static boolean copyBFile(File src, File tar) throws Exception {
		if (src.isFile()) {
			InputStream is = new FileInputStream(src);
			OutputStream op = new FileOutputStream(tar);
			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedOutputStream bos = new BufferedOutputStream(op);
			byte[] bt = new byte[1024 * 8];
			int len = bis.read(bt);
			while (len != -1) {
				bos.write(bt, 0, len);
				len = bis.read(bt);
			}
			bis.close();
			bos.close();
		}
		if (src.isDirectory()) {
			File[] f = src.listFiles();
			tar.mkdir();
			for (int i = 0; i < f.length; i++) {
				copyBFile(f[i].getAbsoluteFile(), new File(tar.getAbsoluteFile() + File.separator
						+ f[i].getName()));
			}
		}
		return true;
	}

	/** 移动文件 **/
	public static boolean moveFile(File src, File tar) throws Exception {
		if (copyBFile(src, tar)) {
			deleteFile(src);
			return true;
		}
		return false;
	}

	/** 删除文件 **/
	public static void deleteFile(File f) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; ++i) {
					deleteFile(files[i]);
				}
			}
		}
		f.delete();
	}

	/** 获取MIME类型 **/
	public static String getMIMEType(String name) {
		String type = "";
		String end = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
		if (end.equals("apk")) {
			return "application/vnd.android.package-archive";
		} else if (end.equals("mp4") || end.equals("avi") || end.equals("3gp")
				|| end.equals("rmvb")) {
			type = "video";
		} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf")
				|| end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else if (end.equals("txt") || end.equals("log")) {
			type = "text";
		} else {
			type = "*";
		}
		type += "/*";
		return type;
	}
}
